package com.css.fxfzypg.manage.sampling.controller;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.base.exception.ServiceException;
import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.logInfo.SysLog;
import com.css.fxfzypg.manage.sampling.repository.entity.SamplingEntity;
import com.css.fxfzypg.manage.sampling.repository.entity.StructureFeature;
import com.css.fxfzypg.manage.sampling.service.SamplingService;
import com.css.fxfzypg.manage.sampling.vo.SamplingParams;
import com.css.fxfzypg.manage.sampling.vo.SamplingSurveyPointVo;
import com.css.fxfzypg.manage.sampling.vo.SavePieVo;
import com.css.fxfzypg.modules.hypergraph.service.HypergraphService;
import com.css.fxfzypg.util.PlatformPageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


/**
 * 抽样调查点概况信息接口
 */
@RestController
@RequestMapping("/sampling")
@Slf4j
public class SamplingController {
    @Autowired
    SamplingService samplingService;

    @Autowired
    HttpServletRequest request;

    @Resource
    HypergraphService hypergraphService;

    /**
     * 新增调研点
     *
     * @param samplingEntity
     * @return
     */
    @SysLog("新增抽样调查点")
    @PostMapping("/insertSurvey")
    public RestResponse insertSurvey(@RequestBody SamplingEntity samplingEntity) {
        RestResponse response = null;
        try {
            boolean res = samplingService.insertSurvey(samplingEntity);
            if (res) {
                //刷新指定超图工作空间数据源数据集
                boolean bool = hypergraphService.getWorkspaceReload("ypg_sampling_survey_new");
                response = RestResponse.succeed("新增成功!");
                response.setMessage("新增成功!");
            } else {
                response = RestResponse.fail("新增失败!");
            }
        } catch (Exception e) {
            String errormessage = "新增失败!";
            log.error(errormessage, e);
            response = RestResponse.succeed(errormessage);
        }
        return response;
    }

    /**
     * 保存并提交
     *
     * @param samplingEntity
     * @return
     */
    @SysLog("保存并提交抽样调查点")
    @PostMapping("/saveAndSubmit")
    public RestResponse saveAndSubmit(@RequestBody SamplingEntity samplingEntity) {
        RestResponse response = null;
        try {
            boolean res = samplingService.saveAndSubmit(samplingEntity);
            if (res) {
                //刷新指定超图工作空间数据源数据集
                boolean bool = hypergraphService.getWorkspaceReload("ypg_sampling_survey_new");
                response = RestResponse.succeed("保存并提交成功!");
                response.setMessage("保存并提交成功!");
            } else {
                response = RestResponse.fail("保存并提交失败!");
            }
        } catch (Exception e) {
            String errormessage = "保存并提交失败!";
            log.error(errormessage, e);
            response = RestResponse.fail(errormessage);
        }
        return response;
    }

    /**
     * 查询已提交和未提交列表
     *
     * @param submitFlag
     * @return
     */
    @GetMapping("/querySubmitOrNot")
    public RestResponse querySubmitOrNot(HttpServletRequest request, String submitFlag, String taskCode, String userId) {
        RestResponse response = null;
        try {
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            Map<String, Object> map = samplingService.querySubmitOrNot(submitFlag, taskCode, curPage, pageSize, userId);
            response = RestResponse.succeed(map);
        } catch (Exception e) {
            log.error("获取列表信息失败!", e);
            response = RestResponse.fail("获取列表信息失败!");
        }
        return response;
    }

    /**
     * 根据id更新提交状态
     *
     * @param map
     * @return
     */
    @SysLog("提交抽样调查点")
    @PostMapping("/updateIsSubmit")
    public RestResponse updateIsSubmit(@RequestBody Map<String, String> map) {
        RestResponse response = null;
        try {
            boolean res = samplingService.updateIsSubmit(map);
            if (res) {
                response = RestResponse.succeed("提交成功!");
                response.setMessage("提交成功!");
            } else {
                response = RestResponse.fail("提交失败!");
            }
        } catch (Exception e) {
            String errormessage = "提交失败";
            log.error(errormessage, e);
            response = RestResponse.fail(errormessage);
        }
        return response;
    }

    /**
     * 根据id查询详情页数据
     *
     * @param id
     * @return
     */
    @SysLog("查询抽样调查点详情")
    @GetMapping("/queryData")
    public RestResponse queryData(String id) {
        RestResponse response = null;
        JSONObject json = new JSONObject();
        try {
            SamplingEntity samplingEntity = samplingService.queryData(id);
            json.put("data", samplingEntity);
            json.put("message", "查询详情页成功!");
            response = RestResponse.succeed(json);
        } catch (Exception e) {
            String errormessage = "查询详情页失败";
            log.error(errormessage, e);
            response = RestResponse.fail(errormessage);
        }
        return response;
    }

    /**
     * 修改详情页数据
     *
     * @param samplingEntity
     * @return
     */
    @SysLog("修改抽样调查点")
    @PostMapping("/modifyData")
    public RestResponse modifyData(@RequestBody SamplingEntity samplingEntity) {
        RestResponse response = null;
        try {
            log.debug("修改抽样调查点,param:{}", JSONObject.toJSONString(samplingEntity));
            boolean res = samplingService.modifyData(samplingEntity);
            if (res) {
                response = RestResponse.succeed("修改成功!");
                response.setMessage("修改成功!");
            } else {
                response = RestResponse.fail("修改失败!");
            }
        } catch (Exception e) {
            String errormessage = "修改失败!";
            log.error(errormessage, e);
            response = RestResponse.fail(errormessage);
        }
        return response;
    }

    /**
     * 保存典型结构特征
     *
     * @param structureFeature
     * @return
     */
    @PostMapping("/saveStructureFeature")
    public RestResponse saveStructureFeature(@RequestBody StructureFeature structureFeature) {
        RestResponse response = null;
        try {
            boolean res = samplingService.saveStructureFeature(structureFeature);
            if (res) {
                response = RestResponse.succeed("修改成功!");
                response.setMessage("修改成功!");
            } else {
                response = RestResponse.fail("修改失败!");
            }
        } catch (Exception e) {
            String errormessage = "修改失败!";
            log.error(errormessage, e);
            response = RestResponse.fail(errormessage);
        }
        return response;
    }

    /**
     * 修改并提交
     *
     * @param samplingEntity
     * @return
     */
    @SysLog("修改并提交抽样调查点")
    @PostMapping("/modifyAndSubmit")
    public RestResponse modifyAndSubmit(@RequestBody SamplingEntity samplingEntity) {
        RestResponse response = null;
        try {
            boolean res = samplingService.modifyAndSubmit(samplingEntity);
            if (res) {
                response = RestResponse.succeed("修改成功!");
                response.setMessage("修改成功!");
            } else {
                response = RestResponse.fail("修改失败!");
            }
        } catch (Exception e) {
            String errormessage = "修改失败!";
            log.error(errormessage, e);
            response = RestResponse.fail(errormessage);
        }
        return response;
    }

    /**
     * 抽样调查点数据列表查询
     *
     * @param request
     * @param queryParams
     * @return
     */
    @SysLog("查询抽样调查点数据列表")
    @GetMapping("/querySamplingList")
    public RestResponse querySamplingData(HttpServletRequest request, SamplingParams queryParams) {
        RestResponse response = null;
        try {
            log.debug("params:{}", JSONObject.toJSONString(queryParams));
            int curPage = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int pageSize = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            Map<String, Object> map = samplingService.querySamplingData(queryParams, curPage, pageSize);
            response = RestResponse.succeed(map);
        } catch (Exception e) {
            log.error("查询抽样调查点数据列表数据失败!", e);
            response = RestResponse.fail("查询抽样调查点数据列表数据失败!");
        }
        return response;
    }

    /**
     * 根据id删除数据
     *
     * @param
     * @return
     */
    @SysLog("删除抽样调查点")
    @PostMapping("/deleteById")
    public RestResponse deleteSampling(String ids) {
        RestResponse response = null;
        try {
            boolean res = samplingService.deleteSampling(ids);
            if (res) {
                response = RestResponse.succeed("删除成功!");
                response.setMessage("删除成功!");
            } else {
                response = RestResponse.fail("删除失败!");
            }
        } catch (Exception e) {
            log.error("删除失败!", e);
            response = RestResponse.fail("删除失败!");
        }
        return response;
    }

    /**
     * 获取某任务下 当前登录人和无分配人的数据
     *
     * @param taskCode
     * @param userId
     * @return
     */
    @GetMapping("/getDataByUserId")
    public RestResponse getDataByUserId(String taskCode, String userId) {
        RestResponse response = null;
        try {
            List<SamplingEntity> samplingEntities = samplingService.getDataByUserId(taskCode, userId);
            response = RestResponse.succeed(samplingEntities);
            response.setMessage("获取 " + taskCode + " 任务,当前登录人数据和未分配人数据成功!");
        } catch (Exception e) {
            log.error("获取 " + taskCode + " 任务,当前登录人数据和未分配人数据失败!", e);
            response = RestResponse.fail("获取  " + taskCode + " 任务,当前登录人数据和未分配人数据失败!");
        }
        return response;
    }

    /**
     * 获取抽样调查点地图分布数据
     *
     * @return
     */
    @GetMapping("/querySamplingMap")
    public RestResponse querySamplingMap(SamplingParams queryParams) {
        RestResponse response = null;
        try {
            List<SamplingParams> samplingList = samplingService.querySamplingMap(queryParams);
            response = RestResponse.succeed(samplingList);
            response.setMessage("获取抽样调查点地图分布数据成功");
        } catch (Exception e) {
            log.error("获取抽样调查点地图分布数据失败!", e);
            response = RestResponse.fail("获取抽样调查点地图分布数据失败!");
        }
        return response;
    }

    /**
     * 获取某任务下所有调研点
     *
     * @param taskCode
     * @return
     */
    @GetMapping("/getSamplingByTaskCode")
    public RestResponse getDataByTaskCode(String taskCode) {
        RestResponse response = null;
        try {
            List<SamplingEntity> samplingList = samplingService.getSamplingByTaskCode(taskCode);
            response = RestResponse.succeed(samplingList);
            response.setMessage("获取 " + taskCode + " 任务下所有调研点成功");
        } catch (Exception e) {
            log.error("获取 " + taskCode + " 任务下所有调研点失败!", e);
            response = RestResponse.fail("获取 " + taskCode + " 任务下所有调研点失败!");
        }
        return response;
    }

    /**
     * 导入excel
     *
     * @param file
     * @return
     */
    @SysLog("导入抽样调查点")
    @PostMapping("/uploadSampling")
    public RestResponse uploadSampling(@RequestParam("file") MultipartFile file) {
        RestResponse response = null;
        try {
            Map<String, Object> map = samplingService.uploadSampling(file);
            boolean res = ((Boolean) map.get("res")).booleanValue();
            if (res) {
                //刷新指定超图工作空间数据源数据集
                boolean bool = hypergraphService.getWorkspaceReload("ypg_sampling_survey_new");
                response = RestResponse.succeed("上传成功!");
                response.setMessage("上传成功!");
            } else {
                response = RestResponse.fail("上传失败!");
                response.setMessage(map.get("mess").toString());
            }
        } catch (ServiceException se) {
            log.error(se.getMessage(), se);
            return RestResponse.fail(se.getMessage());
        } catch (Exception e) {
            String errormessage = "上传失败!";
            log.error(errormessage, e);
            response = RestResponse.fail(errormessage);
        }
        return response;
    }

    /**
     * excel导出
     *
     * @param queryParams
     * @throws Exception
     */
    @SysLog("导出抽样调查点")
    @PostMapping("/exportSampling")
    public RestResponse exportSampling(HttpServletResponse response, SamplingParams queryParams) {
        RestResponse restResponse = null;
        try {
            samplingService.exportSampling(response, queryParams);
            restResponse.succeed("导成出功");
        } catch (Exception e) {
            String errormessage = "导出失败!";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 根据经纬度获取距离最近的调查点(APP端)
     */
    @GetMapping("/getNearestSamplingAPP")
    public RestResponse getNearestSamplingAPP(String longitude, String latitude, String taskCode) {
        RestResponse restResponse = null;
        try {
            SamplingEntity samplingEntity = samplingService.getNearestSamplingAPP(longitude, latitude, taskCode);
            restResponse.succeed(samplingEntity);
            restResponse.setMessage("获取成功!");
        } catch (Exception e) {
            String errormessage = "获取失败!";
            log.error(errormessage, e);
            restResponse = RestResponse.fail(errormessage);
        }
        return restResponse;
    }

    /**
     * 抽样调查点分页查询
     *
     * @return
     */
    @GetMapping("getSamplingSurveyPoint")
    public RestResponse getSamplingSurveyPoint(SamplingSurveyPointVo samplingSurveyPointVo, HttpServletRequest request) {
        return samplingService.getSamplingSurveyPoint(samplingSurveyPointVo, request);
    }

    //保存饼状图
    @PostMapping("savePie")
    public RestResponse savePie(@RequestBody SavePieVo savePieVo) {
        try {
            samplingService.savePie(savePieVo.getId(), savePieVo.getTypePie(), savePieVo.getYearsPie());
            return RestResponse.succeed("保存成功!");
        } catch (Exception e) {
            log.error("保存失败!", e);
            return RestResponse.fail("保存失败!");
        }
    }
}